class_name Interactor
extends Area2D

#region 属性
@export var entity:Entity
var interactable_items:Array[Interactable] = []
var last_interactable_item:Interactable
var connect_obj_dict:Dictionary[Signal,ConnectObj] = {}
var is_interacting:bool = false
#endregion
#region 字段
var cur_interable_item:Interactable:
	get:
		return Utils.get_or_default(interactable_items,0,null)
#endregion
#region 信号
signal start_interact_event(interactor:Interactor,interactable:Interactable)
signal interacting_event(interactor:Interactor,interactable:Interactable)
signal end_interact_event(interactor:Interactor,interactable:Interactable)
#endregion

#region 基类方法
#endregion
#region 公共方法
func init(entity:Entity):
	self.entity = entity
	connect_obj_dict[area_entered] = ConnectObj.new(area_entered,[_on_area_entered])
	connect_obj_dict[area_exited] = ConnectObj.new(area_exited,[_on_area_exited])
func start_interact():
	if cur_interable_item:
		cur_interable_item.start_interact(self)
		start_interact_event.emit(self,cur_interable_item)
		set_process(true)
func interacting():
	if cur_interable_item:
		cur_interable_item.interacting()
		interacting_event.emit(self,cur_interable_item)
func end_interact():
	if last_interactable_item:
		last_interactable_item.end_interact(self)
		last_interactable_item.set_seleted(false)
		end_interact_event.emit(self,last_interactable_item)
		set_process(false)
		last_interactable_item = cur_interable_item
		if cur_interable_item:
			cur_interable_item.set_seleted(true)
func add_interactable_item(interactable:Interactable):
	if not interactable_items.has(interactable):
		interactable_items.append(interactable)
		interactable_items.sort_custom(func (x,y):return (x.global_position - global_position).length() < (y.global_position - global_position).length())
		update_interactable_item()
func remove_interactable_item(interactable:Interactable):
	if interactable_items.has(interactable):
		interactable_items.erase(interactable)
		interactable_items.sort_custom(func (x,y):return (x.global_position - global_position).length() < (y.global_position - global_position).length())
		update_interactable_item()
func update_interactable_item():
	if last_interactable_item != cur_interable_item and last_interactable_item:
		end_interact()
	last_interactable_item = cur_interable_item
	if cur_interable_item:
		cur_interable_item.set_seleted(true)
#endregion
#region 私有方法
func _on_area_entered(area:Area2D):
	if area is Interactable:
		add_interactable_item(area)
func _on_area_exited(area:Area2D):
	if area is Interactable:
		remove_interactable_item(area)
#endregion
#region 生命周期函数
func _process(delta: float) -> void:
	interacting()
func _notification(what: int) -> void:
	if what == NOTIFICATION_PREDELETE:
		for connect_obj:ConnectObj in connect_obj_dict.values():
			if connect_obj:
				connect_obj.disconnect_all()
#endregion
